package com.technology.education.ext

import android.app.Activity
import android.view.View
import com.google.gson.Gson
import com.technology.education.data.AppData
import com.technology.education.data.SpKeys
import com.technology.education.data.model.CallEventModel
import com.technology.education.data.model.IMCustomData
import com.technology.education.data.model.VideoCallModel
import com.technology.education.ui.teacher.upload_answer.UploadAnswerActivity
import com.tencent.imsdk.v2.*
import com.tencent.liteav.trtccalling.TUICalling
import com.tencent.liteav.trtccalling.TUICallingImpl
import com.tencent.liteav.trtccalling.model.TRTCCalling
import com.tencent.liteav.trtccalling.model.impl.base.CallModel
import com.tencent.liteav.trtccalling.model.impl.base.SignallingData
import com.tencent.qcloud.tuicore.TUILogin
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.util.startActivity
import java.nio.charset.Charset
import java.util.*

/**
 *@author:create by BZY
 *Date: 2022/3/24 08
 * 腾讯云相关方法
 */

/**
 * 初始化IM
 */
fun Activity.initIM() {

    TUILogin.init(
        applicationContext,
        AppData.SDK_ID,
        V2TIMSDKConfig(),
        object : V2TIMSDKListener() {
            override fun onKickedOffline() {
                super.onKickedOffline()
                toast("您的账号已在其他设备登录")
                reLogin()
            }

            override fun onUserSigExpired() {
                super.onUserSigExpired()
                toast("您的登录已过期,请重新登录")
                reLogin()
            }
        })
    V2TIMManager.getInstance().addSimpleMsgListener(object : V2TIMSimpleMsgListener() {
        override fun onRecvC2CCustomMessage(
            msgID: String?,
            sender: V2TIMUserInfo?,
            customData: ByteArray?
        ) {
            super.onRecvC2CCustomMessage(msgID, sender, customData)
            try {
                customData?.let {
                    val customStr = it.toString(Charset.defaultCharset())
                    val bean = Gson().fromJson(customStr, IMCustomData::class.java)
                    when (bean.type) {
                        SpKeys.REFRESH_ORDER_DETAIL -> postEventBus(bean.type, bean.value)
                    }
                }
            } catch (e: Exception) {
                showLog(e.toString())
            }

        }
    })

}

/**
 * 登录到IM
 */
fun loginIM(sign: String) {
    if (V2TIMManager.getInstance().loginStatus == V2TIMManager.V2TIM_STATUS_LOGINED) {
        ///如果当前IM已经登录,则不再重复调用
        return
    }
    TUILogin.login(AppData.USER_ID, sign, object : V2TIMCallback {
        override fun onSuccess() {
            getAppViewModel().userInfo.value?.let {
                TUICallingImpl.sharedInstance(appContext).setUserAvatar(it.avatar ?: "", null)
                TUICallingImpl.sharedInstance(appContext).setUserNickname(it.name, null)
            }
        }

        override fun onError(p0: Int, p1: String?) {
            showLog("login----$p1---$p0")
        }

    })
}

fun generateRoomID(): Int {
    val random = Random()
    return random.nextInt(TRTCCalling.ROOM_ID_MAX - TRTCCalling.ROOM_ID_MIN + 1) + TRTCCalling.ROOM_ID_MIN
}

/**
 * 教师接单之后发送消息通知学生,学生端刷新订单详情
 */

fun sendTakeOrder(orderId: String, receiver: String) {
    getAppViewModel().pushMessage(orderId, SpKeys.REFRESH_ORDER_DETAIL, receiver)
//    sendCustomMsg(IMCustomData(SpKeys.REFRESH_ORDER_DETAIL, orderId), receiver)
}

/**
 * 老师开始视频辅导,发送呼叫信令,同时通知学生订单详情进行刷新
 * 这里接收的回调都是教师端的
 */
fun videoCall(orderId: String, receiver: String, roomId: Int) {

    val model = VideoCallModel(AppData.USER_ID, receiver, SignallingData().apply {
        version = 4
        businessID = "av_call"
        platform = "android"
        callAction = 0
        setcallid(orderId)
        callType = 2
        data = SignallingData.DataInfo().apply {
            cmd = "videoCall"
            room_id = roomId
            recordId = orderId
            userIDs = listOf(receiver)
        }
        setRoomId(roomId)
    })
    getAppViewModel().pushMessage(Gson().toJson(model), SpKeys.VIDEO_CALL, receiver)
    TUICallingImpl.sharedInstance(appContext)
        .call(arrayOf(receiver), TUICalling.Type.VIDEO, orderId, roomId)
    TUICallingImpl.sharedInstance(appContext).enableFloatWindow(true)
    TUICallingImpl.sharedInstance(appContext)
        .setCallingListener(object : TUICalling.TUICallingListener {
            override fun clickEvent(type: TUICalling.ClickType?) {
                showLog("clickEvent----$type")
                if (AppData.MEMBER_TYPE == "1") {
                    ///只有教师才有控制权
                    when (type) {
                        TUICalling.ClickType.SHOW_LOCAL, TUICalling.ClickType.SHOW_REMOTE -> {
                            toast("切换成功")
                            getAppViewModel().pushMessage(
                                orderId,
                                if (type == TUICalling.ClickType.SHOW_REMOTE) SpKeys.SHOW_REMOTE else SpKeys.SHOW_LOCAL,
                                receiver
                            )
                        }
                        TUICalling.ClickType.TEACH_RECORD -> {
                            postEventBus(SpKeys.TEACH_RECORD, orderId)
                        }
                    }
                }

            }

            override fun shouldShowOnCallView(): Boolean {
                return true
            }

            override fun onCallStart(
                userIDs: Array<out String>?,
                type: TUICalling.Type?,
                role: TUICalling.Role?,
                tuiCallingView: View?
            ) {

            }

            override fun onCallEnd(
                userIDs: Array<out String>?,
                type: TUICalling.Type?,
                role: TUICalling.Role?,
                totalTime: Long
            ) {
                showLog("onCallEnd--${userIDs!![0]}-----")
            }

            override fun onCallEvent(
                event: TUICalling.Event?,
                type: TUICalling.Type?,
                role: TUICalling.Role?,
                message: String?
            ) {
                showLog("onCallEvent--$message--$event")
            }

            override fun endVideo() {
                showLog("endVideo-----------")
                if (AppData.MEMBER_TYPE == "1") {
                    postEventBus(SpKeys.FINISH_VIDEO, orderId)
                } else {
                    postEventBus(SpKeys.REFRESH_ORDER_DETAIL, orderId)
                }
                TRTCCalling.sharedInstance(appContext).hangup()
            }

            override fun onUserEnter(userId: String?) {
                showLog("onUserEnter-----------$userId")
                if (AppData.MEMBER_TYPE == "1") {
                    postEventBus(SpKeys.START_VIDEO, orderId)
                }
            }

            override fun onError(code: Int, msg: String?) {
                showLog("onError:$code--$msg")
                getAppViewModel().pushMessage(Gson().toJson(
                    CallEventModel(
                         orderId,
                        receiver,
                        msg?:"",
                        CallModel.VIDEO_CALL_ACTION_HANGUP
                    )
                ), SpKeys.VIDEO_HANG_UP, receiver)
            }

            override fun onEvent(inviteId: String?, data: String?, type: Int) {
                showLog("onEvent-----$type---$data--$inviteId")
                getAppViewModel().pushMessage(
                    Gson().toJson(
                        CallEventModel(
                            inviteId ?: orderId,
                            receiver,
                            data ?: "",
                            type
                        )
                    ), SpKeys.VIDEO_HANG_UP, receiver
                )
            }

        })
}

/**
 * 拒绝接听
 */
fun rejectVideo() {
}

/**
 * 接听
 */
fun acceptVideo() {
}

/**
 * 发布自定义消息,这里只有在线用户可以收到消息
 */
fun sendCustomMsg(data: IMCustomData, receiver: String) {
    val str = Gson().toJson(data).toByteArray()
    V2TIMManager.getMessageManager()
        .sendMessage(V2TIMManager.getMessageManager().createCustomMessage(str),
            receiver,
            null,
            0,
            true,
            V2TIMOfflinePushInfo().apply {
                desc = "新的辅导消息"
            },
            object : V2TIMSendCallback<V2TIMMessage> {
                override fun onSuccess(p0: V2TIMMessage?) {
                }

                override fun onError(p0: Int, p1: String?) {
                }

                override fun onProgress(p0: Int) {
                }

            })
}